package com.insigma.business.qrcode.soldier.service.impl;

import com.insigma.business.qrcode.soldier.service.ISequenceAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;


public class SequenceAdapterImpl implements ISequenceAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(SequenceAdapterImpl.class);

    private Integer maxWorkerNum = 8;

    @Override
    public void register(long workId) {

    }

    @Override
    public long getNextWorkId() {
        return getWorker(maxWorkerNum);
    }

    @Override
    public long getTimestamp() {
        return System.currentTimeMillis();
    }

    public static long getWorker(long maxNum) {
        long id = 0L;
        try {
            InetAddress ip = InetAddress.getLocalHost();
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            if (network == null) {
                id = 1L;
            } else {
                byte[] mac = network.getHardwareAddress();
                if (null != mac) {
                    id = ((0x000000FF & (long) mac[mac.length - 2]) | (0x0000FF00 & (((long) mac[mac.length - 1]) << 8))) >> 6;
                    id = id % (maxNum + 1);
                }
            }
        } catch (Exception e) {
            LOGGER.warn(" getDatacenterId: " + e.getMessage());
        }
        return id;
    }

    public static void main(String[] args) {
        SequenceAdapterImpl.getWorker(8);
    }

}
